<template>
  <div class="warp">
    <div class="warp_auto">
      <div class="warp_top">
        <div class="jiansuo-box">
          <span class="label">住院号：</span>
          <el-input
            v-model="visitId"
            class="input"
            clearable
            placeholder="请输入住院号"
          />
        </div>

        <div class="jiansuo-box">
          <span class="label">病人姓名：</span>
          <el-input
            v-model="visitIdname"
            clearable
            class="input"
            placeholder="请输入病人姓名"
          />
        </div>

        <div class="jiansuo-box">
          <span class="label">性别：</span>
          <el-select
            v-model="sexVal"
            placeholder="请选择"
            clearable
            class="input"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>

        <div class="jiansuo-box">
          <span class="label">诊断关键词：</span>
          <el-input
            v-model="diagnosisName"
            clearable
            class="input"
            placeholder="请输入诊断关键词"
          />
        </div>


        <div class="jiansuo-box">
          <span class="label">当前状态：</span>
          <el-select
            v-model="current"
            placeholder="请选择"
            clearable
            class="input"
          >
            <el-option
              v-for="item in optioncurrent"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <span class="label">当前科室：</span>
          <el-select
            v-model="value"
            placeholder="请选择"
            clearable
            class="input"
          >
            <el-option
              v-for="item in listarr"
              :key="item.id"
              :label="item.department_name"
              :value="item.department_code"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <span class="label">入科时间：</span>
          <el-date-picker
            v-model="enterStartTime"
            type="daterange"
            align="right"
            unlink-panels
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </div>
        <div class="jiansuo-box">
          <span class="label">出科时间：</span>
          <el-date-picker
            v-model="exitStartTime"
            type="daterange"
            align="right"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </div>
        <div class="jiansuo-box">
          <el-button
            type="primary"
            icon="el-icon-search"
            class="btn"
            @click="btn"
          >检索
          </el-button>
        </div>
      </div>
      <el-card shadow="hover">
        <el-popover
          placement="top-start"
          width="60"
          trigger="hover"
          content="导出到Excel表"
          style="float: right;margin-left:20px;margin-bottom: 10px"
        >
          <el-button
            slot="reference"
            type="primary"
            class="daochu"
            @click="Excel"
          >导出
            <i class="el-icon-question"/>
          </el-button>
        </el-popover>
        <el-button
          class="input-item"
          icon="el-icon-plus"
          style="float: right;margin-bottom: 10px"
          @click="(translate = true), increase()"
        >新增患者
        </el-button
        >

        <el-table
          :data="arr"
          stripe
          style="width: 100%"
          :header-cell-style="{ background: '#d2e0f9', color: '#606266' }"
        >
          <el-table-column type="expand" fixed>
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="住院时间：">
                  <span>{{ props.row.visit_time.substring(0, 19) }}</span>
                </el-form-item>
                <el-form-item label="入科床位：">
                  <span>{{ props.row.bed_code }}</span>
                </el-form-item>
                <el-form-item label="是否非计划：">
                  <span>{{
                      props.row.unplanned === "1"
                        ? "是"
                        : props.row.unplanned === "2"
                          ? "否"
                          : ""
                    }}</span>
                </el-form-item>
                <el-form-item label="病情：">
                  <span>{{ props.row.illness_state }}</span>
                </el-form-item>
                <el-form-item label="责任医生：">
                  <span>{{ props.row.docterName }}</span>
                </el-form-item>
                <el-form-item label="责任护士：">
                  <span>{{ props.row.nurseName }}</span>
                </el-form-item>
                <el-form-item label="最新手术时间：">
                  <span>{{ props.row.operation_time.substring(0, 19) }}</span>
                </el-form-item>
                <el-form-item label="最新手术名称：">
                  <span>{{ props.row.operation_name }}</span>
                </el-form-item>
                <el-form-item label="死亡时间：">
                  <span>{{ props.row.death_time }}</span>
                </el-form-item>
                <el-form-item label="诊断：">
                  <span>{{ props.row.diagnosis_name }}</span>
                </el-form-item>
                <el-form-item label="过敏史：">
                  <span>{{ props.row.allergies }}</span>
                </el-form-item>
                <el-form-item label="阳性：">
                  <span>{{ props.row.positive }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            label="序号"
            fixed
            align="center"
            type="index"
            width="90"
          />
          <el-table-column
            label="住院号"
            prop="visit_id"
            width="140"
            align="center"
          />
          <el-table-column
            label="病历号"
            prop="visit_code"
            width="140"
            align="center"
          />
          <el-table-column
            label="姓名"
            prop="name"
            width="100"
            align="center"
          />
          <el-table-column label="性别" width="100" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{
                  scope.row.sex === '1' ? "男" : scope.row.sex === '2' ? "女" : ""
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="年龄" prop="age" width="100" align="center"/>
          <el-table-column label="入科时间" width="180" align="center">
            <template slot-scope="scope">
              <span>
                {{ scope.row.enter_time.substring(0, 19) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="出科时间" width="180" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{
                  scope.row.exit_time == "" ? "---" : scope.row.exit_time
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="当前状态" width="140" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{
                  scope.row.flag == "1" ? "在科" : scope.row.exit_type
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="当前科室" width="200" align="center">
            <template slot-scope="scope">
              {{ getNameByCode(scope.row.department_code) }}
            </template>
          </el-table-column>
          <el-table-column label="转出科室" width="140">
            <template slot-scope="scope">
              {{ getNameByCode(scope.row.to_department_code) }}
            </template>
          </el-table-column>
          <el-table-column label="转入科室" width="140">
            <template slot-scope="scope">
              {{ getNameByCode(scope.row.in_department_code) }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="200"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleData(scope.row, scope.$index)"
              >选择
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <div class="paging">
        <el-pagination
          :current-page="start"
          :page-size="PageSize"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <el-dialog
        title="新增"
        :visible.sync="translate"
        width="700px"
      >
        <el-form
          ref="asymptomatic"
          :rules="rules"
          :model="asymptomatic"
          label-width="100px"
        >
          <div class="add-dialog">
            <el-form-item label="姓名" prop="name">
              <el-input style="width: 200px" v-model="asymptomatic.name"/>
            </el-form-item>
            <el-form-item label="床号" prop="bedCode">
              <el-select
                v-model="asymptomatic.bedCode"
                clearable
                placeholder="请选择"
                class="el-inputer"
              >
                <el-option
                  v-for="item in luoxuanjizai"
                  :key="item.id"
                  :label="item.bedCode"
                  :value="item.bedCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="住院号" prop="visitId">
              <el-input style="width: 200px" v-model="asymptomatic.visitId"/>
            </el-form-item>
            <el-form-item label="病历号" prop="visitCode">
              <el-input style="width: 200px" v-model="asymptomatic.visitCode"/>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="asymptomatic.sex">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input style="width: 200px" v-model="asymptomatic.age"/>
            </el-form-item>
            <el-form-item label="入院时间:" prop="visitTime">
              <el-date-picker
                v-model="asymptomatic.visitTime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                style="width: 200px"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="入科时间:" prop="enterTime">
              <el-date-picker
                v-model="asymptomatic.enterTime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                style="width: 200px"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </div>
          <el-form-item label="诊断：" prop="diagnosisname">
            <el-input v-model="asymptomatic.diagnosisname"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="translate = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitFormthrees('asymptomatic')"
          >保 存
          </el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import {patientInfoSave} from "@/utils/utils";
import {
  patientgetList,
  deparqueryList,
  patientgetBedNullPatientList,
  insert, downloadPatient,
} from "@/api/table";
import {getTenantId} from "@/utils/auth";

export default {
  data() {
    return {
      translate: false,
      luoxuanjizai: [],
      asymptomatic: {
        name: "",
        bedCode: "",
        visitId: "",
        visitCode: "",
        sex: "",
        age: "",
        enterTime: "",
        visitTime: "",
        diagnosisname: "",
        departmentCode: "重症医学科",
        wardCode: "重症医学科护理站",
      },
      rules: {
        diagnosisname: [
          {required: true, message: "请输入诊断", trigger: "blur"},
        ],
        name: [{required: true, message: "请输入姓名", trigger: "blur"}],
        bedCode: [{required: true, message: "请输入床号", trigger: "blur"}],
        visitId: [{required: true, message: "请输入住院号", trigger: "blur"}],
        enterTime: [
          {required: true, message: "请输入入科时间", trigger: "blur"},
        ],
        visitTime: [
          {required: true, message: "请输入入院时间", trigger: "blur"},
        ],
        sex: [{required: true, message: "请输入性别", trigger: "blur"}],
        age: [{required: true, message: "请输入年龄", trigger: "blur"}],
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      enterStartTime: "",
      exitStartTime: "",
      visitId: "",
      visitIdname: "",
      diagnosisName: '',
      del: false,
      options: [
        {
          id: "1",
          value: "1",
          label: "男",
        },
        {
          id: "2",
          value: "2",
          label: "女",
        },
      ],
      optioncurrent: [
        {
          id: "0",
          value: "0",
          label: "出科",
        },
        {
          id: "1",
          value: "1",
          label: "在科",
        },
      ],
      value: "",
      sexVal: "",
      current: "",
      graduate: "",
      arr: [],
      listarr: [],
      departMap: {},
      valuequ: "",
      start: 1, // 默认显示第几页
      totalCount: 0, // 总条数，根据接口获取数据长度(注意：这里不能为空)
      pgeSizes: [10, 20, 30, 40], // 个数选择器（可修改）
      PageSize: 10, // 默认每页显示的条数（可修改）
    };
  },
  created() {
    deparqueryList().then((res) => {
      this.listarr = res.data;
      res.data.forEach((item)=>{
        this.departMap[item.department_code] = item.department_name;
      });
    });
  },
  mounted() {
    this.list(this.PageSize, this.start);
  },
  methods: {
    //根据科室code获取科室名称
    getNameByCode(code) {
      return this.departMap[code] ?? code;
    },
    Excel() {
      // downloadPatient()
      axios({
        //url: 'http://localhost:9528/api/patient/downloadPatient', // 本地
        url: "/api/patient/downloadPatient", //打包
        method: "post",
        responseType: "blob", // 也可以使用blob
        headers:{
          'tenantId' : getTenantId()
        },
      })
        .then((res) => {
          if (res) {
            const blob = new Blob([res.data], {
              type: "application/vnd.ms-excel;charset=utf-8",
            }); // res就是接口返回的文件流了
            const objectUrl = URL.createObjectURL(blob);
            const elink = document.createElement("a");
            elink.download = "病人查询.xls"; // 下载文件名称,
            elink.style.display = "none";
            elink.href = objectUrl;
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    increase() {
      (this.asymptomatic = {
        name: "",
        bedCode: "",
        visitId: "",
        visitCode: "",
        sex: "",
        age: "",
        enterTime: "",
        visitTime: "",
        diagnosisname: "",
        departmentCode: "重症医学科",
        wardCode: "重症医学科护理站",
      }),
        patientgetBedNullPatientList().then((res) => {
          this.luoxuanjizai = res.data;
        });
    },
    submitFormthrees(asymptomatic) {
      this.$refs[asymptomatic].validate((valid) => {
        if (valid) {
          insert({
            wardCode: this.asymptomatic.wardCode,
            departmentCode: this.asymptomatic.departmentCode,
            name: this.asymptomatic.name,
            bedCode: this.asymptomatic.bedCode,
            visitId: this.asymptomatic.visitId,
            visitCode: this.asymptomatic.visitCode,
            sex: this.asymptomatic.sex,
            age: this.asymptomatic.age,
            enterTime: this.asymptomatic.enterTime,
            visitTime: this.asymptomatic.visitTime,
            diagnosisName: this.asymptomatic.diagnosisname,
          }).then((res) => {
            this.translate = false;
            this.btn();
          });
        } else {
          this.translate = true;
          this.$message({
            message: "请填写必填项！",
            type: "warning",
            duration: 1500,
          });
          this.dialogFormVisible = true;
          return false;
        }
      });
    },
    // 搜索按钮
    btn() {
      this.start = 1;
      this.list(this.PageSize, this.start);
    },

    //选中病人
    handleData(row, index) {
      //对与床位列表选中的患者信息差异化数据进行一致性处理
      let tempData = Object.assign('', row)

      tempData.bedCode = row.bed_code;
      tempData.department_name = this.getNameByCode(row.department_code);
      tempData.flag = row.flag == 1 ? "在科" : row.exit_type;
      tempData.sex = row.sex === '1' ? "男" : row.sex === '2' ? "女" : "";
      tempData.unplanned = row.unplanned == "1" ? "是" : row.unplanned == "2" ? "否" : "";
      tempData.patient_id = row.id;
      tempData.bed_code_name = row.bed_code;

      patientInfoSave(tempData);
    },
    list(pageSize, start) {
      patientgetList({
        visitId: this.visitId,
        name: this.visitIdname,
        sex: this.sexVal === "" ? null : Number(this.sexVal),
        diagnosisName: this.diagnosisName,
        enterStartTime: this.enterStartTime[0],
        enterEndTime: this.enterStartTime[1],
        exitStartTime: this.exitStartTime[0],
        exitEndTime: this.exitStartTime[1],
        flag: this.current === "" ? null : Number(this.current),
        exitType: this.graduate,
        departmentCode: this.value,
        size: pageSize,
        start: start,
      }).then((res) => {
        this.arr = res.data;
        this.totalCount = res.totalCount;
      });
    },
    // 每页显示的条数
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.PageSize = val;
      // 点击每页显示的条数时，显示第一页
      this.list(val, 1);
      // 注意：在改变每页显示的条数时，要将页码显示到第一页
      this.start = 1;
    },
    // 显示第几页
    handleCurrentChange(val) {
      this.visitId = "";
      this.visitIdname = "";
      // 改变默认的页数
      this.start = val;
      // 切换页码时，要获取每页显示的条数
      this.list(this.PageSize, (this.start = val));
    }
  }
};
</script>
<style lang="scss" scoped>
.add-dialog{
  display: flex;
  flex-wrap: wrap;
  .el-form-item{
    width: 50%;
  }

}
</style>
